package com.ynjtc.desserts.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ynjtc.desserts.common.WrapMapper;
import com.ynjtc.desserts.common.Wrapper;
import com.ynjtc.desserts.entity.Category;
import com.ynjtc.desserts.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author: lihua
 * @Date: 2025/9/15 14:16
 * @Version: v1.0.0
 * @Description:
 **/
@RestController
@RequestMapping("/category")
@CrossOrigin(origins = "http://localhost:5173")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @PostMapping("/add")
    public Wrapper<Category> addCategory(@RequestBody Category category){
        if(StringUtils.isAnyEmpty(category.getName(),category.getCategoryDescribe())){
            return WrapMapper.error("分类名称或描述不能为空！");
        }else {
            category.setStatus(1);
            category.setCreateTime(LocalDateTime.now());
            Category categoryNew = categoryService.addCategory(category);
            if( categoryNew == null){
                return WrapMapper.error("名称重复");
            }else {
                return WrapMapper.ok();
            }
        }
    }

    @GetMapping("/category")
    public Wrapper<?> getCategory(@Param("num") Integer num,
                                  @Param("page") Integer page,
                                  @Param("name") String name,
                                  @Param("describe") String describe){
        num = num == null ? 10 : num;
        page = page == null ? 1 : page;
        Page<Category> pages = categoryService.getCategory(num,page,name,describe);
        return WrapMapper.ok(pages);
    }

    @PostMapping("/delete")
    public Wrapper<Category> deleteCategory(@RequestBody List<Integer> ids){
        if( ids == null )
            return WrapMapper.error("参数错误");
        categoryService.deleteCategory(ids);
        return WrapMapper.ok();
    }

    @PostMapping("/modify")
    public Wrapper<Category> modifyCategoryInfo(@RequestBody Category category){
        if(category.getId() == null || category.getName()==null || category.getCategoryDescribe() ==null) {
            return WrapMapper.error("参数错误");
        } else{
            Category newCategory = categoryService.updateCategoryInfo(category);
            if( newCategory == null)
                return WrapMapper.error("id 错误");
            else
                return WrapMapper.ok(newCategory);
        }
    }

}
